<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div style="margin-bottom: 10px">
        <el-button slot="right" class="filter-item"
          :disabled="crud.order.orderStatus === 'PASS' || crud.order.orderStatus === 'CLOSE' " size="mini" type="primary"
          @click="addRow()">
          新增
        </el-button>
        <el-button slot="right" class="filter-item"
           size="mini" type="primary"
          @click="submit()">
          保存
        </el-button>
        <el-button slot="right" class="filter-item" size="mini" type="warning"
                    @click="copyOrder" v-permission="permission.copy">
          复制
        </el-button>
        <el-button slot="right" class="filter-item" size="mini" type="success"
          :disabled="crud.order.orderStatus !== 'SAVE'" :loading="crud.passLoading"
          @click="crud.doDetailPassOrReject('PASS', id)">
          审核
        </el-button>
        <el-button slot="right" class="filter-item" size="mini" type="info" :loading="crud.rejectLoading"
          :disabled="crud.order.orderStatus !== 'PASS'" @click="crud.doDetailPassOrReject('REJECT', id)">
          反审
        </el-button>
        <el-button
          slot="right"
          :loading="crud.downloadLoading"
          class="filter-item"
          size="mini"
          type="warning"
          @click="crud.preView"
          :disabled="$route.params.id == 'add'"
        >打印
        </el-button>
        <el-button
          slot="right"
          :loading="crud.downloadLoading"
          class="filter-item"
          size="mini"
          type="warning"
          @click="crud.preView1"
          :disabled="$route.params.id == 'add'"
        >打印预览
        </el-button>
        <el-button slot="right" :disabled="crud.order.orderStatus !== 'PASS'" class="filter-item" size="mini"
          type="info" :loading="crud.rejectLoading" @click="showGenerateFee">
          生成费用
        </el-button>
        <el-button slot="right" :disabled="user.userId !== crud.order.currentNodeUserId" class="filter-item" size="mini"
                   type="info" :loading="crud.rejectLoading" @click="approveFlow(2)">
          流程审核
        </el-button>
        <el-button slot="right" :disabled="user.userId !== crud.order.currentNodeUserId" class="filter-item" size="mini"
                   type="info" :loading="crud.rejectLoading" @click="approveFlow(3)">
          驳回
        </el-button>
      </div>
      <j-dialog title="请选择银行"
                :visible.sync="showBank"
                is-mask
      >
        <table-select
          :tableColumns="[{prop:'name',label:'名称',width: '280'}]"
          :value.sync="tempBankId"
          placeholder="请选择银行"
          url="api/basBank"
          style="width:100%;"
          :params="{sort: 'seq desc'}"
        ></table-select>
        <el-button slot="right"  class="filter-item" size="mini"
                   type="info" :loading="crud.rejectLoading" @click="selectBank">
          确认
        </el-button>
      </j-dialog>
      <el-form style="margin-bottom: 10px" size="small" label-width="120px" ref="orderForm" :rules="rules"
        :model="crud.order">
        <el-row :gutter="10">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="合同开始时间" prop="startDate">
              <el-date-picker
                :disabled="crud.order.orderStatus === 'PASS' || crud.order.orderStatus === 'CLOSE'"
                v-model="crud.order.startDate" type="date" format="yyyy - MM - dd" value-format="yyyy-MM-dd" style="width: 100%;" default-value
                placeholder="请选择合同开始时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="合同结束时间" prop="endDate">
              <el-date-picker
                :disabled="crud.order.orderStatus === 'PASS' || crud.order.orderStatus === 'CLOSE'"
                v-model="crud.order.endDate" type="date" format="yyyy - MM - dd" value-format="yyyy-MM-dd" style="width: 100%;" default-value
                placeholder="请选择合同结束时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="单据编号">
              <el-input :disabled="true" v-model="crud.order.sourceCode" placeholder="系统自动生成"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="合同名称" prop="name">
              <el-input
                :disabled="crud.order.orderStatus === 'CLOSE'"
                v-model="crud.order.name" placeholder="请输入合同名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="合同类型" prop="type">
              <el-select
                :disabled="crud.order.orderStatus === 'PASS' || crud.order.orderStatus === 'CLOSE'"
                v-model="crud.order.type" class="filter-item" clearable placeholder="请选择合同类型" size="small"
                style="width: 100%;">
                <el-option v-for="item in dict.t_fee_order_type" :key="item.id" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="供应商">
              <zSelect
                :disabled="crud.order.orderStatus === 'PASS' || crud.order.orderStatus === 'CLOSE'"
                :clearable="true" :value.sync="crud.order.supplierId==0?null:crud.order.supplierId" :showName="crud.order.supplierName"
                url="api/dropDown/basCustomerList" :params="{ isContact: '1,2' }" style="width:  100%"
                @change="changeSupplier" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="客户">
              <zSelect
                :disabled="crud.order.orderStatus === 'PASS' || crud.order.orderStatus === 'CLOSE'"
                :clearable="true" :value.sync="crud.order.customerId==0?null:crud.order.customerId" :showName="crud.order.customerName"
                url="api/dropDown/basCustomerList" :params="{ isContact: '0,2' }" style="width:  100%"
                @change="changeCustomer" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="状态">
              <el-select :disabled="true" v-model="crud.order.orderStatus" class="filter-item" clearable
                placeholder="请选择状态" size="small" style="width: 100%;">
                <el-option v-for="item in dict.common_order_status" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="费用结算方式">
              <el-select  class="edit-input" v-model="crud.order.settleType" placeholder="请选择">
                <el-option
                  v-for="(item,index) in settleTypeList"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="备注">
              <el-input v-model="crud.order.remark"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-dialog  title="打印预览"
                  destroy-on-close
                  v-dialogDrag
                  close-on-press-escape
                  :visible.sync="showPdf" append-to-body width="50vw">
        <j-pdf :src="pdfSrc" ></j-pdf>
      </el-dialog>
      <el-dialog
        title="请选择打印模板"
        :visible.sync="crud.printConfig.pringDialog"
        width="30%"
      >
        <jPrintConfig groupId="feeContract"
                      v-if="crud.printConfig.pringDialog"
                      @getPrintId="detailedPrint"
                      :isPreview="crud.printConfig.isPreview"
        ></jPrintConfig>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" stripe border v-loading="crud.loading" :data="crud.order.feeContractFeeDtoList" size="small"
        style="width: 100%;" :show-summary="true" :summary-method="sumMoney"
        @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" width="58" label="序号" />
        <el-table-column width="160" v-if="columns.visible('goodsBrandName')" prop="goodsBrandName" label="品牌">
          <template slot-scope="{row}">
            <zSelect :disabled="crud.order.orderStatus === 'PASS' || crud.order.orderStatus === 'CLOSE'"
              :value.sync="row.goodsBrandId" :showName="row.goodsBrandName" :label="row.goodsBrandName"
              placeholder="请选择品牌" url="api/dropDown/basGoodsBrandList" @change="changeBrand(row, $event)">
            </zSelect>
          </template>
        </el-table-column>
        <el-table-column width="160" v-if="columns.visible('subjectName')" prop="subjectName" label="费用科目">
          <template slot-scope="{row}">
            <el-select-tree :disabled="crud.order.orderStatus === 'PASS' || crud.order.orderStatus === 'CLOSE'"
              placeholder="请选择内容" :filterable="true" :data="subjects" v-model="row.subjectId"
              :props="{ value: 'id', label: 'name', children: 'children' }" @nodeClick="changeSubjects($event, row)">
            </el-select-tree>
          </template>
        </el-table-column>
        <el-table-column width="180"  v-if="crud.order.settleType === 2" prop="goodsBrandName" label="商品">
          <template slot-scope="{row}">
            <jtg-select-plus ref="productRef"
                             v-model="row.goodsId"
                             :initValue="row.goodsName"
                             typeName="SALE"
                             :customerId="crud.order.customerId"
                             @change="changeGoods($event,row)"
                             url="productList"/>
          </template>
        </el-table-column>
        <el-table-column   v-if="crud.order.settleType === 2" prop="taxPrice" label="含税单价" width="150" >
          <template slot-scope="scope">
            <el-input :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'"
                      @input.native="crud.inuptCount(scope, 'taxPrice',taxAmountChangeFeeAmount)"
                      oninput="value=value.replace(/[^\d^\.]/g,'')"
                      maxlength="12"
                      v-model.lazy="scope.row.taxPrice"
                      style="width: 100%"/>
          </template>
        </el-table-column>
        <el-table-column  v-if="crud.order.settleType === 2"  prop="taxBoxPrice" label="含税箱价" width="150">
          <template slot-scope="scope">

            <el-input :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'"
                      @input.native="crud.inuptCount(scope, 'taxBoxPrice',taxAmountChangeFeeAmount)"
                      oninput="value=value.replace(/[^\d^\.]/g,'')"
                      maxlength="12"
                      v-model.lazy="scope.row.taxBoxPrice"
                      style="width: 100%"/>
          </template>
        </el-table-column>
        <el-table-column width="250" v-if="crud.order.settleType === 2" prop="taxPrice" label="辅数量" >
          <template slot-scope="scope">
            <span v-if="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'">{{ scope.row.boxNum }}{{ scope.row.boxUnitName }}</span>
            <el-input v-else
                      @input.native="crud.inuptCount(scope, 'boxNum',taxAmountChangeFeeAmount)"
                      v-model="scope.row.boxNum"
                      style="width: 45%!important;">
              <template slot="append" >{{scope.row.boxUnitName}}</template>
            </el-input>
            <span v-if="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'">{{ scope.row.mainNum }}{{ scope.row.mainUnitName }}</span>
            <el-input v-else
                      @input.native="crud.inuptCount(scope, 'mainNum',taxAmountChangeFeeAmount)"
                      v-model="scope.row.mainNum"
                      style="width: 45%!important;">
              <template slot="append" >{{scope.row.mainUnitName}}</template>
            </el-input>
          </template>
        </el-table-column>
        <el-table-column width="180" v-if="columns.visible('feeAmount')" prop="feeAmount" label="费用总额">
          <template slot-scope="{row,$index}">
            <el-input-number style="width:100%"
              :disabled="crud.order.orderStatus === 'PASS' || crud.order.orderStatus === 'CLOSE'"
              v-model="row.feeAmount" :precision="2" :step="0.1" :min="0" @change="changeMoney($event, row)" />
          </template>
        </el-table-column>
        <el-table-column width="120" v-if="columns.visible('isFq')" prop="isFq" label="是否分期">
          <template slot-scope="{row,$index}">
            <el-select :disabled="crud.order.orderStatus === 'PASS' || crud.order.orderStatus === 'CLOSE'"
              v-model="row.isFq" class="filter-item" clearable placeholder="是否分期" size="small" style="width: 100%;"
              @change="changeFq($event, row)">
              <el-option v-for="item in dict.common_yes_or_no" :key="item.id" :label="item.label" :value="item.value" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column width="150" v-if="columns.visible('fqMonth')" prop="fqMonth" label="分摊月数">
          <template slot-scope="{row,$index}">
            <el-input-number :disabled="row.fqMonthDisabled " style="width:100%" v-model="row.fqMonth" :precision="0"
              :step="1" :min="0" @change="changeMonth($event, row)" />
          </template>
        </el-table-column>
        <el-table-column width="120" v-if="columns.visible('monthAmount')" prop="monthAmount" label="每月费用" />
        <el-table-column width="180" v-if="columns.visible('supplierRate')" prop="supplierRate" label="供应商承担比例(%)">
          <template slot-scope="{row,$index}">
            <el-input-number style="width:100%"
              :disabled="crud.order.orderStatus === 'PASS' || crud.order.orderStatus === 'CLOSE' "
              v-model="row.supplierRate" :precision="2" :step="1" :min="0" :max="100"
              @change="changeSupplierRate($event, row)" />
          </template>
        </el-table-column>
        <el-table-column width="120" v-if="columns.visible('supplierAmount')" prop="supplierAmount" label="供应商费用" />
        <el-table-column width="160" v-if="columns.visible('ownRate')" prop="ownRate" label="自理比例(%)">
          <template slot-scope="{row,$index}">
            <el-input-number :disabled="crud.order.orderStatus === 'PASS' || crud.order.orderStatus === 'CLOSE'"
              style="width:100%" v-model="row.ownRate" :precision="2" :step="1" :min="0" :max="100"
              @change="changeOwnRate($event, row)" />
          </template>
        </el-table-column>
        <el-table-column width="160" v-if="columns.visible('ownAmount')" prop="ownAmount" label="自理费用" />
        <el-table-column width="160" v-if="columns.visible('generateAmount')" prop="generateAmount" label="已生成费用" />
        <el-table-column width="160" v-if="columns.visible('remainAmount')" prop="remainAmount" label="剩余费用">
          <template slot-scope="{row,$index}">
            <span>{{ row.feeAmount - row.generateAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column width="160" v-if="columns.visible('remark')" prop="remark" label="备注">
          <template slot-scope="{row,$index}">
            <el-input :disabled="crud.order.orderStatus === 'PASS' || crud.order.orderStatus === 'CLOSE'"
              v-model="row.remark" placeholder="请输入备注"></el-input>
            <!-- <el-input :disabled=" crud.order.orderStatus === 'CLOSE'"
              v-model="row.remark" placeholder="请输入备注"></el-input> -->
          </template>
        </el-table-column>
        <el-table-column :render-header="crud.renderHeader" label="操作" fixed="right" align="center">
          <template slot-scope="scope">
            <el-button slot="reference" class="el-icon-delete opration_icon_btn"
              :disabled="crud.order.orderStatus === 'PASS' || crud.order.orderStatus === 'CLOSE'"
              style="border: none;width: auto;height: auto" @click="delAddRow(scope.$index)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
      <flow-step-node v-if="crud.order.flowStepNode" :flowStepNode="crud.order.flowStepNode" :cur-node="crud.order.currentNodeName">

      </flow-step-node>
      <el-dialog title="生成费用单" :visible.sync="showFeeOrder" width="60%">
        <el-table ref="table" stripe border height="300" :row-class-name="crud.tableRowClassName"
          v-loading="feeOrderLoading" :data="feeOrderTableData" size="small" style="width: 100%;">
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('subjectName')" prop="subjectName"
            label="费用科目" />
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('feeAmount')" prop="feeAmount"
            label="费用总额" />
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('generateAmount')"
            prop="generateAmount" label="已生成费用" />
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('curGenerateAmount')"
            prop="curGenerateAmount" label="本次生成费用" />
        </el-table>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="showFeeOrder = false">取消</el-button>
          <el-button :loading="crud.cu === 2" type="primary" @click="feeOrderConfirm">确认</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import CRUD, {crud, form, header, presenter} from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import crudFeeContract from "@/api/erp/feeContract";
import {getTree} from "@/api/erp/basSubject";
import {isEmpty} from "@/utils";
import ElSelectTree from 'el-select-tree'
import {Notification} from "element-ui";
import jPrintConfig from '@/components/jPrintConfig/jPrintConfig'
import jtgSelectPlus from '../../../components/select/JtgSelectPlus.vue'
import store from "@/store";
import {mapGetters} from "vuex";
import {handleApprove} from "@/api/erp/approveFlow";
import JDialog from "@/components/jDialog/jDialog.vue";
import FlowStepNode from "@/components/flowStepNode/index.vue";
// crud交由presenter持有
const defaultCrud = CRUD({
  title: '费用合同返点',
  url: 'api/feeContract/detail',
  sort: 'id,desc',
  params() {
    const href = location.href.split('/')
    if (href[5].includes('copyId')) {
      return {
        id: href[5].replace("copyId=",""),
      }
    } else {
      return {
        id: href[href.length - 1] == 'add' ? 0 : href[href.length - 1], page: 0, size: 999,
      }
    }
  },

  order: {
    customerId: null,
    supplierId: null,
    feeContractFeeDtoList: []
  },
  crudMethod: { ...crudFeeContract }
})
const defaultForm = {
  id: null,
  orderId: null,
  goodsBrandId: null,
  goodsBrandCode: null,
  goodsBrandName: null,
  subjectId: null,
  subjectCode: null,
  subjectName: null,
  feeAmount: null,
  isFq: null,
  fqMonth: null,
  monthAmount: null,
  supplierRate: null,
  supplierAmount: null,
  ownRate: null,
  ownAmount: null,
  generateAmount: null,
  remainAmount: null,
  seq: null,
  remark: null,
  createUserId: null,
  createUserCode: null,
  createUserName: null,
  createTime: null,
  updateUserId: null,
  updateUserCode: null,
  updateUserName: null,
  updateTime: null,
  settleType:1
}
export default {
  name: 'feeContractFee',
  components: {
    FlowStepNode,
    JDialog, pagination, crudOperation, rrOperation, udOperation, ElSelectTree, jPrintConfig, jtgSelectPlus },
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  dicts: ['t_fee_order_type', 'common_yes_or_no', 'common_order_status'],
  data() {
    return {

      permission: {
        add: ['admin', 'feeContract:add'],
        edit: ['admin', 'feeContract:edit'],
        del: ['admin', 'feeContract:del'],
        import: ['admin', 'feeContract:import'],
        export: ['admin', 'feeContract:export'],
        copy: ['admin', 'feeContract:copy'],
        upload: ['admin', 'feeContract:upload'],
        download: ['admin', 'feeContract:download'],
      },
      subjects: [],
      showPdf: false,
      settleTypeList:[
        {label:'现金',value:1},
        {label:'产品',value:2},
      ],
      rules: {
        startDate: [
          { required: true, message: '合同开始时间不能为空', trigger: 'blur' }
        ],
        endDate: [
          { required: true, message: '合同结束时间不能为空', trigger: 'blur' }
        ],
        // name: [
        //   { required: true, message: '合同名称不能为空', trigger: 'blur' }
        // ],
        type: [
          { required: true, message: '合同类型不能为空', trigger: 'blur' }
        ],
      },
      showFeeOrder: false,
      feeOrderLoading: false,
      feeOrderTableData: [],
      showBank:false,
      bankId:null,
      tempBankId: null
    }
  },
  computed: {
    ...mapGetters([
      'user',
    ])
  },
  watch: {},
  destroyed() {
    this.crud.setItemInfo("feeContractFeeDetail_add")
  },
  created() {
    this.getSubjects()
    if (this.$route.params.id == 'add') {
      if (this.crud.getItemInfo("feeContractFeeDetail_add")) {
        return false
      }
      this.crud.order = {
        customerId: null,
        supplierId: null,
        feeContractFeeDtoList: []
      }
    }
    if (window.location.href.includes('copy')){
      this.crud.order.createUserId = null
      this.crud.order.updateUserId = null
      this.crud.order.closeUserId = null
      this.crud.order.auditUserUserId = null
    }
  },
  methods: {
    // 获取数据前设置好接口地址
    [CRUD.HOOK.beforeRefresh]() {
      return true
    }, // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
    },
    [CRUD.HOOK.afterRefresh](crud, form) {
      if (this.$route.params.id != 'add') {
        if (!isEmpty(this.crud.order.feeContractFeeDtoList) && this.crud.order.feeContractFeeDtoList.length > 0) {
          this.crud.order.feeContractFeeDtoList.forEach(row => {
            if (row.isFq == 1) {
              row.fqMonthDisabled = true
            } else {
              row.fqMonthDisabled = false
            }
          })
        }
      }
      const href = location.href.split('/')
      if(href[5].includes('copyId')){
        this.crud.order.orderStatus = 'SAVE'
      }
    },
    submit() {
      this.$refs['orderForm'].validate(valid => {
        if (!valid) {
          return
        }
        var oDate1 = new Date(this.crud.order.startDate);
        var oDate2 = new Date(this.crud.order.endDate);
        if (oDate1.getTime() > oDate2.getTime()) {
          this.$message({
            message: '合同开始时间不能大于合同结束时间',
            type: 'warning'
          })
          return
        }
        if(crud.order){}
        const bank_rules = [
          {name: '品牌', value: 'goodsBrandId'},
          {name: '费用科目', value: 'subjectId'},
          {name: '费用科目', value: 'subjectId'},
          {name: '费用总额', value: 'feeAmount'}
        ]
        let feeContractFeeDtoList = this.crud.order.feeContractFeeDtoList
        if (!this.tableRules(feeContractFeeDtoList, bank_rules, "请新增费用信息")) {
          return;
        }
        this.save()
      })
    },
    tableRules(list, rules, nullMsg) {
      let flag = true
      if (list === null || list.length === 0) {
        Notification.error({title: nullMsg})
        return false
      }
      rules.forEach(rule => {
        for (let i = 0; i < list.length; i++) {
          if (list[i][rule.value] == undefined || list[i][rule.value] == null || list[i][rule.value] == '') {
            Notification.error({title: '序号【' + (i + 1) + '】' + rule.name + '不能为空'})
            flag = false
            break
          }
        }
      })
      return flag
    },
    taxAmountChangeFeeAmount(row){
      row.feeAmount = row.taxAmount
    },
    save() {
      let that = this
      that.crud.loadingOpen()
      this.crud.order.project = 'fee'
      const href = location.href.split('/')
      if (href[5].includes('copyId')) {
        this.crud.order.id = 0
        for (let i = 0; i < this.crud.order.feeContractFeeDtoList.length; i++) {
          this.crud.order.feeContractFeeDtoList[i].id = null
          this.crud.order.feeContractFeeDtoList[i].orderId = null
          this.crud.order.feeContractFeeDtoList[i].generateAmount = null
          this.crud.order.feeContractFeeDtoList[i].remainAmount = null
        }

      }
      let params = this.crud.order
      for (let i = 0; i < params.feeContractFeeDtoList.length; i++) {
        params.feeContractFeeDtoList[i].remainAmount = params.feeContractFeeDtoList[i].feeAmount - params.feeContractFeeDtoList[i].generateAmount
      }
      if (this.crud.order.orderStatus === 'PASS')params.isEditWithoutReject = 1
      crudFeeContract.add(params).then(res => {
        if (res.success) {
          this.crud.order = res.data.order
          let id = this.crud.order.id
          if (this.$route.params.id == 'add' || href[5].includes('copyId')) {
            this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.push({ params: { id } })
            this.crud.cleanItemInfo("feeContractFeeDetail_add")
          }
          this.$message({
            message: '保存成功',
            type: 'success'
          })
          that.crud.loadingClose()
        } else {
          that.crud.loadingClose()
          this.$message({
            message: res.msg,
            type: 'warning'
          })
        }

      }).catch((res) => {
        that.crud.loadingClose()
      })
    },
    detailedPrint(val) {
      if (val !== null) {
        console.log(crud)
        this.crud.printConfig.pringDialog = false
        const urlList = window.location.href.split('/')
        const id = urlList[urlList.length - 1 ].split('?')[0]
        this.crud.doPrint(val, [id], this.crud.printConfig.isPreview)
      } else {
        this.$message.error('请选择打印模板')
      }
    },
    addRow() {
      const item = {
        goodsBrandId: null,
        goodsBrandName: null,
        subjectCode: null,
        subjectName: null,
        feeAmount: 0.00,
        isFq: null,
        fqMonth: null,
        monthAmount: null,
        supplierAmount: null,
        supplierRate:100.00,
        ownRate: 0.00,
        ownAmount: null,
        generateAmount: null,
        remark: null,
        goodsId:0,
        goodsName:'',
        taxPrice:0,
        taxBoxPrice:0,
        taxAmount: 0,
        goodsCount: 0
      }
      this.crud.order.feeContractFeeDtoList.push(item);
    },
    getSubjects() {
      getTree().then(res => {
        this.subjects = []
        const subjects = { id: 0, name: '顶级分类', children: [] }
        subjects.children = res.data
        this.subjects.push(subjects)
      })
    },
    changeMoney(value, row) {
      if (!isEmpty(row.fqMonth) && row.isFq == 1 && row.fqMonth > 0) {
        row.monthAmount = (value / row.fqMonth).toFixed(2)
      }
      if (!isEmpty(row.supplierRate) && row.supplierRate > 0) {
        row.supplierAmount = (value * row.supplierRate / 100).toFixed(2)
      }
      if (!isEmpty(row.ownRate) && row.ownRate > 0) {
        row.ownAmount = (value * row.ownRate / 100).toFixed(2)
      }
    },
    changeFq(value, row) {
      if (value == 0) {
        row.fqMonth = null
        row.monthAmount = null
        row.fqMonthDisabled = true
      }
      if (value == 1) {
        row.fqMonthDisabled = false
        if (!isEmpty(row.fqMonth) && !isEmpty(row.monthAmount) && row.monthAmount > 0) {
          row.monthAmount = (value / row.fqMonth).toFixed(2)
        }
      }
    },
    changeMonth(value, row) {
      if (!isEmpty(row.feeAmount) && row.feeAmount > 0) {
        row.monthAmount = (row.feeAmount / value).toFixed(2)
      }
    },
    changeSupplierRate(value, row) {
      if (!isEmpty(row.feeAmount) && row.feeAmount > 0) {
        row.supplierAmount = (row.feeAmount * value / 100).toFixed(2)
      }
      row.ownRate = 100 - value
      this.changeOwnRate(row.ownRate, row)
    },
    changeGoods(goods,row){
      Object.assign(row,goods);
    },
    changeOwnRate(value, row) {
      if (!isEmpty(row.feeAmount) && row.feeAmount > 0) {
        row.ownAmount = (row.feeAmount * value / 100).toFixed(2)
      }
      row.supplierRate = 100 - value
      this.changeSupplierRate(row.supplierRate, row)
    },
    sumMoney({ columns, data }) {
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (column.property === 'feeAmount'
          || column.property === 'monthAmount'
          || column.property === 'supplierAmount'
          || column.property === 'ownAmount') {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index];

        }
      });
      return sums
    },
    copyOrder(e) {
        //内部还款
        this.crud.toCopy(this.crud.order.id,"/fee/feeContractFeeDetail")
    },
    selectBank(){
      this.bankId = this.tempBankId
      this.approveFlow(2)
    },
    //同意
    approveFlow(operationType){
      //如果是财务总监审核的话就需要弹出银行
      if(this.bankId == null && this.sourceType === "FD" && operationType === 2){
        this.showBank = true
        return
      }
      const data = {
        bankId:this.bankId,
        flowId:this.crud.order.approveFlowId,
        operationType,
        sourceType:1,
        sourceId:this.crud.order.id
      }
      handleApprove(data)
    },
    delAddRow(i) {
      if (this.$route.params.id !== 'add') {
        this.$confirm('此操作将直接删除此条产品记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.crud.order.feeContractFeeDtoList.splice(i, 1)
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      } else {
        this.crud.order.feeContractFeeDtoList.splice(i, 1)
      }
    },
    showGenerateFee() {
      this.feeOrderTableData = []
      for (let i = 0; i < this.crud.order.feeContractFeeDtoList.length; i++) {
        const {
          subjectId,
          subjectName,
          feeAmount,
          isFq,
          monthAmount,
          generateAmount
        } = this.crud.order.feeContractFeeDtoList[i]
        let curGenerateAmount = feeAmount
        if (isFq === 1) {
          curGenerateAmount = monthAmount
        }
        const item = {
          subjectId: subjectId,
          subjectName: subjectName,
          feeAmount: feeAmount,
          generateAmount: generateAmount,
          curGenerateAmount: curGenerateAmount
        }
        this.feeOrderTableData.push(item)
      }
      console.log(this.feeOrderTableData)
      this.showFeeOrder = true
    },
    feeOrderConfirm() {
      let that = this
      that.crud.loadingOpen()
      let ids = []
      ids.push(this.crud.order.id)
      crudFeeContract.generateFeeOrder(ids).then(res => {
        that.crud.loadingClose()
        if (res.status == 200) {
          this.showFeeOrder = false
          this.crud.cleanItemInfo("feeContractFeeDetail_add")
          this.crud.refresh()
          this.$message.success('生成成功')
        } else {
          this.$message.success('生成失败')
        }
      }).catch(e => {
        that.crud.loadingClose()
        this.$message.success('生成失败')
      })
    },
    changeSubjects(e, row) {
      row.subjectCode = e.code
      row.subjectName = e.name
    },
    changeSupplier(e) {
      this.crud.order.supplierId = e.id
      this.crud.order.supplierName = e.name
    },
    changeCustomer(e) {
      this.crud.order.customerId = e.id
      this.crud.order.customerName = e.name
    },
    changeBrand(row, e) {
      row.goodsBrandCode = e.code
      row.goodsBrandName = e.name
    }
  }
}
</script>

<style scoped>
.table-img {
  display: inline-block;
  text-align: center;
  background: #ccc;
  color: #fff;
  white-space: nowrap;
  position: relative;
  overflow: hidden;
  vertical-align: middle;
  width: 32px;
  height: 32px;
  line-height: 32px;
}
</style>
